package com.xm.xmds1705083.service.service.impl;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.xm.xm.dto.ResultDto;
import com.xm.xm.dto.SearchDto;
import com.xm.xm.util.ErrorCode;
import com.xm.xm.util.ValidateUtils;
import com.xm.xmds1705083.service.mapper.DuoduoVoteRecordsMapper;
import com.xm.xmds1705083.service.mapper.DuoduoVoteMapper;
import com.xm.xmds1705083.service.mapper.DuoduoVoteOptionMapper;
import com.xm.xmds1705083.service.model.DuoduoVote;
import com.xm.xmds1705083.service.model.DuoduoVoteRecords;
import com.xm.xmds1705083.service.model.DuoduoVoteOption;
import com.xm.xmds1705083.service.service.DuoduoVoteService;
import com.xm.xmds1705083.service.util.GlobalError;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.ibatis.session.RowBounds;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 杭州新苗网络科技有限公司
 * @author meihf
 * @date 2017/06/16
 * @description
*/ 
@Service("duoduoVoteService")
public class DuoduoVoteServiceImpl extends ServiceImpl<DuoduoVoteMapper,DuoduoVote> implements DuoduoVoteService {

    @Autowired
    DuoduoVoteMapper duoduoVoteMapper;

    @Autowired
    DuoduoVoteOptionMapper duoduoVoteOptionMapper;

    @Autowired
    DuoduoVoteRecordsMapper duoduoVoteRecordsMapper;

    protected Logger logger = LogManager.getLogger(getClass());

    @Override
    public ResultDto findTitles(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
            //避免join现在多次查询
            //先查题目
            RowBounds rowBounds = new RowBounds(searchDto.getPageNo(),searchDto.getPageSize());
            EntityWrapper entityWrapper = new EntityWrapper();
            entityWrapper.orderBy("createTime",false);
            List<DuoduoVote> duoduoVoteList = duoduoVoteMapper.selectPage(rowBounds,entityWrapper);
            if (duoduoVoteList.size()==0){
                resultDto.setCode(ErrorCode.C11001);
                resultDto.setMsg(ErrorCode.E11001);
                return resultDto;
            }
            JSONArray duoduoVoteArr = JSONArray.fromObject(duoduoVoteList);
            duoduoVoteArr.forEach((vote)->{
                //查询每个标题下面的选项以及选项id
                ((JSONObject) vote).put("voteId",((JSONObject) vote).remove("id"));
                int voteId = ((JSONObject)vote).getInt("voteId");
                EntityWrapper optionEntity = new EntityWrapper();
                optionEntity.where(" voteId={0} ",voteId);
                List<DuoduoVoteOption> duoduoVoteOptionList = duoduoVoteOptionMapper.selectList(optionEntity);
                JSONArray voteOptionArr = JSONArray.fromObject(duoduoVoteOptionList);
                voteOptionArr.forEach((voteOption)->((JSONObject)voteOption).put("voteOptionId",((JSONObject) voteOption).remove("id")));
                ((JSONObject) vote).put("options",voteOptionArr);
            });
            resultDto.setData(duoduoVoteArr);
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }

    @Override
    public ResultDto voting(SearchDto searchDto) {
        ResultDto resultDto = new ResultDto();
        JSONObject filed = searchDto.getFiled();
        searchDto.setPageNo((searchDto.getPageNo()-1)*searchDto.getPageSize());
        try {
             if (!filed.has("result")){
                  resultDto.setMsg(ErrorCode.E10011);
                  resultDto.setCode(ErrorCode.C10011);
                  return resultDto;
              }else{
                 //将结果转成数组
                 JSONArray result = filed.getJSONArray("result");
                 //先看是否有提交过的记录
                 result.forEach((l)->{
                    int voteId = ((JSONObject)l).getInt("voteId");
                    EntityWrapper entityWrapper = new EntityWrapper();
                    entityWrapper.where(" voteId={0} and userId={1} ",voteId,searchDto.getAppUserId());
                    int selectResult = duoduoVoteRecordsMapper.selectCount(entityWrapper);
                    ((JSONObject) l).put("count",selectResult);
                 });
                 long count = result.stream().filter((l)->((JSONObject)l).getInt("count")>0).count();
                 if (count>0){
                     resultDto.setMsg(GlobalError.E11020);
                     resultDto.setCode(GlobalError.C11020);
                     return resultDto;
                 }
                 //添加投票记录
                 result.forEach(l->{
                     ((JSONObject)l).put("createTime",searchDto.getTime());
                     ((JSONObject)l).remove("count");
                     DuoduoVoteRecords duoduoVoteLog = (DuoduoVoteRecords) JSONObject.toBean(((JSONObject)l),DuoduoVoteRecords.class);
                     duoduoVoteLog.setUserId(searchDto.getAppUserId().intValue());
                     int insertResult = duoduoVoteRecordsMapper.insert(duoduoVoteLog);
                     if (ValidateUtils.isGreaterThan0(insertResult)){
                         resultDto.setMsg("投票成功");
                         //将选项的num+1
                         DuoduoVoteOption option = duoduoVoteOptionMapper.selectList(new EntityWrapper<DuoduoVoteOption>().where(" id={0} ",duoduoVoteLog.getVoteOptionId())).get(0);
                         option.setNum(option.getNum()+1);
                         int resultUpdate =duoduoVoteOptionMapper.updateById(option);
                         if (resultUpdate==1){
                             logger.info("更新投票数成功");
                         }else {
                             logger.info("更新投票数失败");
                         }
                     }else {
                         resultDto.setMsg(ErrorCode.E11003);
                         resultDto.setCode(ErrorCode.C11003);
                     }
                 });
              }
        }catch (RuntimeException e ){
            e.printStackTrace();
            resultDto.setCode(ErrorCode.C10013);
            resultDto.setMsg(ErrorCode.E10013);
        }
        return resultDto;
    }
}

